<template>
  <div class="title-box">
    <div class="title">
      <span>
        已选择：<span class="primary">{{ count }}</span> 个筛选条件
      </span>
      <span class="subtext" @click="isCollapse = !isCollapse">
        {{ isCollapse ? '展开' : '收起' }}
        <el-icon :class="['el-icon-arrow-up', 'icon', { isCollapse }]">
          <ArrowUp />
        </el-icon>
      </span>
    </div>

    <div v-show="!isCollapse">
      <search-group
        ref="advancedSearch"
        class="advanced-search"
        :value="value"
        @update-value="updateValues"
      />
      <div class="btn-group">
        <el-button type="primary" :icon="Search" @click="onSearch" :disabled="isLoading">
          搜索
        </el-button>
        <el-popconfirm
          :icon="InfoFilled"
          icon-color="red"
          title="清空将删除全部搜索条件，确认删除吗"
          @confirm="initSearchData"
          width="288px"
        >
          <template #reference>
            <el-button :icon="RefreshRight"> 清空 </el-button>
          </template>
        </el-popconfirm>

        <el-button :icon="Star" @click="showSaveDialog"> 保存为模板 </el-button>

        <el-button :icon="Edit" @click="usingTemp"> 使用模板 </el-button>
      </div>
    </div>

    <Dialog v-model="saveTmplVisible" title="保存模板" width="450px">
      <flexbox>
        <span style="flex-shrink: 0">模板名称：</span>
        <el-input v-model.trim="tmplName" />
      </flexbox>
      <template #footer>
        <el-button @click="saveTmplVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTemplate">保 存</el-button>
      </template>
    </Dialog>

    <Dialog v-model="useTmplVisible" title="选择模板" width="950px">
      <use-tmpl ref="useTmplRef" v-if="useTmplVisible" />
      <template #footer>
        <el-button @click="useTmplVisible = false">取 消</el-button>
        <el-button type="primary" @click="useTemplate">使 用</el-button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { Search, InfoFilled, RefreshRight, Star, Edit, ArrowUp } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as advanceApi from '@/api/ent/advanceSearch/index'
import SearchGroup from './SearchGroup.vue'
import UseTmpl from './UseTmpl.vue'

const value = ref({
  condition: 'must',
  queryFields: []
})
const isCollapse = ref(false)
const advancedSearch = ref(null)
const useTmplRef = ref(null)
const saveTmplVisible = ref(false)
const useTmplVisible = ref(false)
const tmplName = ref('')
const count = ref(0)
const emit = defineEmits(['search'])
const props = defineProps({
  isLoading: Boolean,
  defaultVal: Object
})

watch(
  () => props.defaultVal,
  (val) => {
    if (Object.keys(val).length) advancedSearch.value.setInitValue(val)
  },
  { deep: true }
)

watch(
  () => value,
  (val) => {
    count.value = getTotalQueryFieldsLength(val.value)
  },
  { deep: true }
)
// 计算筛选条件个数
const getTotalQueryFieldsLength = (data) => {
  let validCount = 0
  if (data.queryFields && data.queryFields.length) {
    data.queryFields.forEach((item) => {
      if (item.queryFields) {
        if (item.queryFields.length) {
          item.queryFields.forEach((items) => {
            validCount++
          })
        }
      } else {
        validCount++
      }
    })
  }
  return validCount
}
const updateValues = (val) => {
  value.value = val
}

const onSearch = async () => {
  await advancedSearch.value.validate()
  emit('search', value.value)
}
const usingTemp = () => {
  sessionStorage.setItem('templateType', 'user')
  useTmplVisible.value = true
}
// 校验
const showSaveDialog = () => {
  const rule = Object.keys(value.value).length == 0
  const rules = value.value?.queryFields?.length == 0
  if (rule || rules) {
    ElMessage.error('请补全查询条件')
  } else {
    tmplName.value = ''
    saveTmplVisible.value = true
  }
}

// 添加模板
const saveTemplate = async () => {
  if (tmplName.value == '') {
    ElMessage.warning('请输入模板名称!')
    return
  }
  const _data = {
    templateName: tmplName.value,
    templateContent: JSON.stringify(value.value),
    templateTag: +new Date()
  }
  await advanceApi.createUserTemp(_data)
  saveTmplVisible.value = false
  ElMessage.success('操作成功，添加 1 个模板')
}

const useTemplate = () => {
  advancedSearch.value.setInitValue(useTmplRef.value.TemlateValue())
  useTmplVisible.value = false
}

const readStorage = () => {
  const storage = sessionStorage.getItem('search_template')
  if (storage) {
    if (storage == `{"condition":"must","queryFields":[]}`) {
      value.value = {
        condition: 'must',
        queryFields: [
          {
            field: 'mobile_phone_count',
            id: 101,
            queryType: 'is_or_not',
            value: '1'
          }
        ]
      }
    } else {
      value.value = JSON.parse(storage)
    }
  } else {
    initSearchData()
  }
}

const saveStorage = () => {
  sessionStorage.setItem('search_template', JSON.stringify(value.value))
}

const initSearchData = () => {
  if (advancedSearch.value)
    advancedSearch.value.setInitValue({
      condition: 'must',
      queryFields: [
        {
          field: 'mobile_phone_count',
          id: 101,
          queryType: 'is_or_not',
          value: '1'
        }
      ]
    })
}

onBeforeMount(() => {
  readStorage()
  window.addEventListener('beforeunload', saveStorage)
})

onBeforeUnmount(() => {
  saveStorage()
  window.removeEventListener('beforeunload', saveStorage)
})
</script>
<style scoped lang="scss">
.title-box {
  max-width: 80%;
  margin: 0 auto;
  .title {
    display: flex;
    justify-content: space-between;
    $text-font-size: 14px;
    font-size: $text-font-size;
    color: #333;
    .primary {
      color: #4b74ff;
    }

    .subtext {
      color: #999;
      cursor: pointer;

      .icon {
        transition: transform 0.3s;

        &.isCollapse {
          transform: rotateX(180deg);
        }
      }
    }
  }
}
.btn-group {
  .el-button {
    margin-right: 10px;
    margin-left: 0;
    font-family: 'HarmonyOS_Regular';
    font-size: 12px;
  }
}
</style>
